// pages/index/index.js
const app = getApp();
import { postAPI } from "../../utils/api.js";
import storageService from "../../utils/storage.js";

Page({
  data: {
    leftPosts: [],
    rightPosts: [],
    loading: false,
    refreshing: false,
    page: 1,
    hasMore: true,
    searchKeyword: "",
    selectedCategory: "all",
    categories: [
      { id: "all", name: "全部", icon: "🏠" },
      { id: "daily", name: "萌宠日常", icon: "🐾" },
      { id: "health", name: "宠物健康", icon: "🏥" },
      { id: "training", name: "宠物训练", icon: "🎯" },
      { id: "food", name: "宠物美食", icon: "🍖" },
      { id: "photo", name: "宠物摄影", icon: "📸" },
      { id: "product", name: "宠物用品", icon: "🛍️" },
    ],
    showSearchBar: false,
    searchHistory: [],
    hotTopics: [],
    userInfo: null,
    isLoggedIn: false,
    // 新增数据
    isLoadingMore: false,
    lastRefreshTime: null,
    searchDebounceTimer: null,
    categoryScrollLeft: 0,
  },

  onLoad() {
    this.initPage();
    this.setupPageConfig();
  },

  onShow() {
    // 检查登录状态
    this.checkLoginStatus();
    // 更新用户信息
    this.updateUserInfo();
    // 检查是否需要刷新数据
    this.checkNeedRefresh();
  },

  onPullDownRefresh() {
    this.refreshPosts();
  },

  onReachBottom() {
    if (this.data.hasMore && !this.data.loading && !this.data.isLoadingMore) {
      this.loadMorePosts();
    }
  },

  // 设置页面配置
  setupPageConfig() {
    // 设置导航栏样式
    wx.setNavigationBarColor({
      frontColor: "#ffffff",
      backgroundColor: "#78C841",
      animation: {
        duration: 300,
        timingFunc: "easeIn",
      },
    });
  },

  // 初始化页面
  initPage() {
    this.loadSearchHistory();
    this.loadHotTopics();
    this.loadPosts();
    this.setData({
      lastRefreshTime: new Date().getTime(),
    });
  },

  // 检查登录状态
  checkLoginStatus() {
    const isLoggedIn = app.globalData.isLoggedIn;
    this.setData({ isLoggedIn });
  },

  // 更新用户信息
  updateUserInfo() {
    const userInfo = app.globalData.userInfo;
    this.setData({ userInfo });
  },

  // 检查是否需要刷新数据
  checkNeedRefresh() {
    const now = new Date().getTime();
    const lastRefresh = this.data.lastRefreshTime;
    const refreshInterval = 5 * 60 * 1000; // 5分钟

    if (now - lastRefresh > refreshInterval) {
      this.refreshPosts();
    }
  },

  // 加载搜索历史
  loadSearchHistory() {
    const searchHistory = storageService.settings.getSearchHistory();
    this.setData({ searchHistory });
  },

  // 加载热门话题
  loadHotTopics() {
    // 模拟热门话题数据
    const hotTopics = [
      { id: 1, name: "萌宠日常", count: 1234, hot: true },
      { id: 2, name: "宠物健康", count: 856, hot: true },
      { id: 3, name: "宠物训练", count: 654, hot: false },
      { id: 4, name: "宠物美食", count: 432, hot: false },
      { id: 5, name: "宠物摄影", count: 321, hot: false },
      { id: 6, name: "新手养宠", count: 567, hot: true },
      { id: 7, name: "宠物用品推荐", count: 234, hot: false },
    ];
    this.setData({ hotTopics });
  },

  // 加载帖子数据
  loadPosts() {
    this.setData({ loading: true });

    // 模拟API调用
    setTimeout(() => {
      const mockPosts = this.generateMockPosts();
      this.distributePosts(mockPosts);
      this.setData({
        loading: false,
        lastRefreshTime: new Date().getTime(),
      });
    }, 800);
  },

  // 生成模拟帖子数据
  generateMockPosts() {
    const mockPosts = [
      {
        id: 1,
        user: {
          id: 1,
          name: "小明",
          avatar: "/images/avatar1.png",
          level: 2,
          verified: true,
        },
        content:
          "今天带我家小猫咪去公园玩，它特别开心！看到其他小动物也很兴奋，真是个好奇宝宝🐱",
        images: ["/images/cat1.jpg", "/images/cat2.jpg"],
        likes: 128,
        comments: 32,
        shares: 15,
        time: "2小时前",
        category: "daily",
        location: "中央公园",
        isLiked: false,
        tags: ["萌宠日常", "猫咪"],
        viewCount: 1234,
      },
      {
        id: 2,
        user: {
          id: 2,
          name: "小红",
          avatar: "/images/avatar2.png",
          level: 1,
          verified: false,
        },
        content:
          "我家狗狗学会了新技能，太棒了！经过一个月的训练，终于学会了握手和坐下，真是聪明的孩子🐕",
        images: ["/images/dog1.jpg"],
        likes: 89,
        comments: 15,
        shares: 8,
        time: "4小时前",
        category: "training",
        location: "家里",
        isLiked: true,
        tags: ["宠物训练", "狗狗"],
        viewCount: 567,
      },
      {
        id: 3,
        user: {
          id: 3,
          name: "宠物医生",
          avatar: "/images/avatar3.png",
          level: 3,
          verified: true,
        },
        content:
          "分享一个宠物健康小贴士：定期给宠物刷牙很重要，可以预防口腔疾病。建议每周刷牙2-3次🦷",
        images: [
          "/images/health1.jpg",
          "/images/health2.jpg",
          "/images/health3.jpg",
        ],
        likes: 256,
        comments: 45,
        shares: 23,
        time: "6小时前",
        category: "health",
        location: "宠物医院",
        isLiked: false,
        tags: ["宠物健康", "口腔护理"],
        viewCount: 2345,
      },
      {
        id: 4,
        user: {
          id: 4,
          name: "美食达人",
          avatar: "/images/avatar4.png",
          level: 2,
          verified: false,
        },
        content:
          "自制宠物零食分享！用鸡胸肉和胡萝卜做的健康小饼干，我家狗狗超爱吃的🍖",
        images: ["/images/food1.jpg", "/images/food2.jpg"],
        likes: 156,
        comments: 28,
        shares: 12,
        time: "8小时前",
        category: "food",
        location: "家里",
        isLiked: false,
        tags: ["宠物美食", "自制零食"],
        viewCount: 890,
      },
    ];

    return mockPosts;
  },

  // 分配帖子到左右两列
  distributePosts(posts) {
    const leftPosts = [];
    const rightPosts = [];

    posts.forEach((post, index) => {
      if (index % 2 === 0) {
        leftPosts.push(post);
      } else {
        rightPosts.push(post);
      }
    });

    this.setData({
      leftPosts,
      rightPosts,
    });
  },

  // 刷新帖子
  refreshPosts() {
    this.setData({
      refreshing: true,
      page: 1,
      hasMore: true,
    });

    setTimeout(() => {
      this.loadPosts();
      this.setData({
        refreshing: false,
        lastRefreshTime: new Date().getTime(),
      });
      wx.stopPullDownRefresh();

      // 显示刷新成功提示
      wx.showToast({
        title: "刷新成功",
        icon: "success",
        duration: 1500,
      });
    }, 1000);
  },

  // 加载更多帖子
  loadMorePosts() {
    if (!this.data.hasMore || this.data.isLoadingMore) return;

    this.setData({ isLoadingMore: true });

    // 模拟加载更多数据
    setTimeout(() => {
      const newPosts = [
        {
          id: this.data.leftPosts.length + this.data.rightPosts.length + 1,
          user: {
            id: 5,
            name: "用户" + (this.data.page + 1),
            avatar: "/images/avatar5.png",
            level: 1,
            verified: false,
          },
          content: "新帖子内容...",
          images: ["/images/pet1.jpg"],
          likes: Math.floor(Math.random() * 100),
          comments: Math.floor(Math.random() * 50),
          shares: Math.floor(Math.random() * 20),
          time: "刚刚",
          category: "daily",
          location: "未知",
          isLiked: false,
          tags: ["萌宠日常"],
          viewCount: Math.floor(Math.random() * 500),
        },
      ];

      // 添加到对应列
      if (this.data.leftPosts.length <= this.data.rightPosts.length) {
        this.setData({
          leftPosts: [...this.data.leftPosts, ...newPosts],
        });
      } else {
        this.setData({
          rightPosts: [...this.data.rightPosts, ...newPosts],
        });
      }

      this.setData({
        isLoadingMore: false,
        page: this.data.page + 1,
        hasMore: this.data.page < 5, // 模拟只有5页数据
      });
    }, 1000);
  },

  // 搜索输入 - 添加防抖
  onSearchInput(e) {
    const keyword = e.detail.keyword;
    this.setData({ searchKeyword: keyword });

    // 清除之前的定时器
    if (this.data.searchDebounceTimer) {
      clearTimeout(this.data.searchDebounceTimer);
    }

    // 设置新的定时器
    const timer = setTimeout(() => {
      if (keyword.trim()) {
        this.performSearch(keyword);
      }
    }, 500);

    this.setData({ searchDebounceTimer: timer });
  },

  // 搜索确认
  onSearchConfirm(e) {
    const keyword = e.detail.keyword;
    if (keyword.trim()) {
      this.performSearch(keyword);
    }
  },

  // 执行搜索
  performSearch(keyword) {
    // 保存搜索历史
    storageService.settings.addSearchHistory(keyword);
    this.loadSearchHistory();

    // 显示搜索结果
    this.setData({
      searchKeyword: keyword,
      showSearchBar: false,
    });

    // 显示搜索中提示
    wx.showLoading({
      title: "搜索中...",
    });

    // 模拟搜索API调用
    setTimeout(() => {
      wx.hideLoading();
      // 这里应该调用搜索API
      console.log("搜索关键词:", keyword);

      // 显示搜索结果提示
      wx.showToast({
        title: `找到相关结果`,
        icon: "success",
        duration: 1500,
      });
    }, 1000);
  },

  // 选择搜索历史
  onSelectSearchHistory(e) {
    const keyword = e.detail.keyword;
    this.performSearch(keyword);
  },

  // 选择热门话题
  onSelectHotTopic(e) {
    const topic = e.detail.topic;
    this.performSearch(topic);
  },

  // 清空搜索历史
  onClearSearchHistory() {
    wx.showModal({
      title: "确认清空",
      content: "确定要清空搜索历史吗？",
      success: (res) => {
        if (res.confirm) {
          storageService.settings.clearSearchHistory();
          this.loadSearchHistory();
          wx.showToast({
            title: "已清空",
            icon: "success",
          });
        }
      },
    });
  },

  // 切换搜索栏显示
  onToggleSearchBar() {
    this.setData({
      showSearchBar: !this.data.showSearchBar,
    });
  },

  // 清除搜索关键词
  onClearSearch() {
    this.setData({
      searchKeyword: "",
    });

    // 清除防抖定时器
    if (this.data.searchDebounceTimer) {
      clearTimeout(this.data.searchDebounceTimer);
      this.setData({ searchDebounceTimer: null });
    }

    // 重新加载所有帖子
    this.loadPosts();
  },

  // 选择分类
  selectCategory(e) {
    const category = e.currentTarget.dataset.category;

    // 添加点击反馈
    wx.vibrateShort({
      type: "light",
    });

    this.setData({
      selectedCategory: category,
    });

    // 根据分类筛选帖子
    this.filterPostsByCategory(category);
  },

  // 根据分类筛选帖子
  filterPostsByCategory(category) {
    wx.showLoading({
      title: "筛选中...",
    });

    setTimeout(() => {
      wx.hideLoading();

      if (category === "all") {
        this.loadPosts();
      } else {
        // 这里应该调用API获取对应分类的帖子
        console.log("筛选分类:", category);

        // 显示筛选结果提示
        const categoryName =
          this.data.categories.find((c) => c.id === category)?.name || category;
        wx.showToast({
          title: `已筛选${categoryName}`,
          icon: "success",
          duration: 1500,
        });
      }
    }, 800);
  },

  // 点赞帖子
  onLikePost(e) {
    const { postId, postIndex, column } = e.detail;

    // 添加触觉反馈
    wx.vibrateShort({
      type: "light",
    });

    // 更新点赞状态
    const posts = this.data[column];
    const post = posts[postIndex];

    if (post.isLiked) {
      post.likes--;
      post.isLiked = false;
    } else {
      post.likes++;
      post.isLiked = true;
    }

    this.setData({
      [column]: posts,
    });

    // 保存点赞状态到本地存储
    storageService.post.setLikeStatus(postId, post.isLiked);

    // 调用API更新点赞状态
    if (post.isLiked) {
      // postAPI.likePost(postId);
    } else {
      // postAPI.unlikePost(postId);
    }
  },

  // 分享帖子
  onSharePost(e) {
    const postId = e.detail.postId;

    wx.showShareMenu({
      withShareTicket: true,
      menus: ["shareAppMessage", "shareTimeline"],
    });
  },

  // 用户点击
  onUserTap(e) {
    const userId = e.detail.userId;
    wx.navigateTo({
      url: `/pages/user/user?id=${userId}`,
    });
  },

  // 发布按钮点击
  onPublishTap() {
    if (!this.data.isLoggedIn) {
      wx.showModal({
        title: "提示",
        content: "请先登录后再发布内容",
        showCancel: false,
      });
      return;
    }

    // 添加触觉反馈
    wx.vibrateShort({
      type: "medium",
    });

    wx.switchTab({
      url: "/pages/post/post",
    });
  },

  // 页面分享
  onShareAppMessage() {
    return {
      title: "宠物社区 - 分享萌宠生活",
      path: "/pages/index/index",
      imageUrl: "/images/share-cover.png",
    };
  },

  // 页面分享到朋友圈
  onShareTimeline() {
    return {
      title: "宠物社区 - 分享萌宠生活",
      imageUrl: "/images/share-cover.png",
    };
  },
});
